import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

export interface Vehicle {
  id: string
  model: string
  fleet: string
  soc: number
  temperature: number
  dischargeTime: number
  maxPower: number
  current: number
  riskLevel: 'low' | 'warning' | 'high'
  thmVector: [number, number, number]
  lastUpdate: string
  selected?: boolean
}

export interface ChargingPile {
  id: string
  name: string
  location: string
  status: 'available' | 'occupied' | 'maintenance'
  remainingPower: number
  predictedConfidence: number
  maxPower: number
  capacity: number
  canAccommodateVehicles: number
}

export const useAppStore = defineStore('app', () => {
  const currentVehicle = ref<Vehicle | null>(null)
  const selectedVehicles = ref<Vehicle[]>([])
  const activeTab = ref('monitor')
  const viewMode = ref<'list' | 'group' | 'compare'>('list')
  const groupBy = ref<'riskLevel' | 'model' | 'fleet'>('riskLevel')

  const vehicles = ref<Vehicle[]>([
    {
      id: 'BYD-HAN-123456',
      model: 'BYD Han EV',
      fleet: '车队A',
      soc: 47.8,
      temperature: 32.5,
      dischargeTime: 25,
      maxPower: 18.5,
      current: -12.3,
      riskLevel: 'high',
      thmVector: [0.82, 0.63, 0.74],
      lastUpdate: '2025-05-06 10:30:00',
      selected: false
    },
    {
      id: 'TESLA-M3-654321',
      model: 'Tesla Model 3',
      fleet: '车队B',
      soc: 60.2,
      temperature: 28.0,
      dischargeTime: 15,
      maxPower: 22.0,
      current: -8.5,
      riskLevel: 'warning',
      thmVector: [0.65, 0.45, 0.85],
      lastUpdate: '2025-05-06 10:29:30',
      selected: false
    },
    {
      id: 'NIO-ES6-789012',
      model: 'NIO ES6',
      fleet: '车队A',
      soc: 85.6,
      temperature: 25.8,
      dischargeTime: 8,
      maxPower: 19.2,
      current: -5.2,
      riskLevel: 'low',
      thmVector: [0.52, 0.25, 0.75],
      lastUpdate: '2025-05-06 10:28:45',
      selected: false
    },
    {
      id: 'XPENG-P7-345678',
      model: 'XPeng P7',
      fleet: '车队C',
      soc: 35.2,
      temperature: 38.5,
      dischargeTime: 35,
      maxPower: 20.2,
      current: -15.8,
      riskLevel: 'high',
      thmVector: [0.95, 0.58, 0.81],
      lastUpdate: '2025-05-06 10:31:15',
      selected: false
    },
    {
      id: 'GEELY-GE11-567890',
      model: 'Geely GE11',
      fleet: '车队B',
      soc: 72.3,
      temperature: 29.8,
      dischargeTime: 12,
      maxPower: 16.5,
      current: -9.2,
      riskLevel: 'warning',
      thmVector: [0.66, 0.20, 0.66],
      lastUpdate: '2025-05-06 10:29:45',
      selected: false
    },
    {
      id: 'AION-S-678901',
      model: 'Aion S',
      fleet: '车队A',
      soc: 91.5,
      temperature: 24.2,
      dischargeTime: 6,
      maxPower: 14.8,
      current: -4.1,
      riskLevel: 'low',
      thmVector: [0.47, 0.10, 0.59],
      lastUpdate: '2025-05-06 10:28:20',
      selected: false
    }
  ])

  const chargingPiles = ref<ChargingPile[]>([
    {
      id: 'CP-001',
      name: '塔塔科技园A区',
      location: '科技园A区停车场',
      status: 'available',
      remainingPower: 45,
      predictedConfidence: 92.5,
      maxPower: 60,
      capacity: 105,
      canAccommodateVehicles: 3
    },
    {
      id: 'CP-002',
      name: '广州科技园B区',
      location: '科技园B区停车场',
      status: 'occupied',
      remainingPower: 0,
      predictedConfidence: 88.2,
      maxPower: 60,
      capacity: 120,
      canAccommodateVehicles: 0
    },
    {
      id: 'CP-003',
      name: '备用区',
      location: '备用充电区',
      status: 'available',
      remainingPower: 30,
      predictedConfidence: 85.0,
      maxPower: 50,
      capacity: 85,
      canAccommodateVehicles: 2
    },
    {
      id: 'CP-004',
      name: '长沙科技园C区',
      location: '科技园C区停车场',
      status: 'available',
      remainingPower: 55,
      predictedConfidence: 90.8,
      maxPower: 75,
      capacity: 150,
      canAccommodateVehicles: 4
    }
  ])

  const dispatchQueue = ref([
    {
      id: 'BYD-HAN-123456',
      model: 'BYD Han EV',
      soc: 47.8,
      priority: 0.56,
      originalPriority: 0.80,
      reason: '反物理SOC跳变',
      hspFactor: 0.30,
      status: 'abnormal'
    },
    {
      id: 'TESLA-M3-654321',
      model: 'Tesla Model 3',
      soc: 60.2,
      priority: 0.50,
      originalPriority: 0.50,
      reason: '正常',
      hspFactor: 0,
      status: 'normal'
    }
  ])

  const availableChargingPiles = computed(() =>
      chargingPiles.value.filter(pile => pile.status === 'available')
  )

  const highRiskVehicles = computed(() =>
      vehicles.value.filter(v => v.riskLevel === 'high')
  )

  const groupedVehicles = computed(() => {
    const groups: Record<string, Vehicle[]> = {}

    vehicles.value.forEach(vehicle => {
      let key = ''
      switch (groupBy.value) {
        case 'riskLevel':
          key = vehicle.riskLevel === 'high' ? '高风险组' :
              vehicle.riskLevel === 'warning' ? '中风险组' : '低风险组'
          break
        case 'model':
          key = vehicle.model
          break
        case 'fleet':
          key = vehicle.fleet
          break
      }

      if (!groups[key]) {
        groups[key] = []
      }
      groups[key].push(vehicle)
    })

    return groups
  })

  const selectedVehicleCount = computed(() =>
      vehicles.value.filter(v => v.selected).length
  )

  const setCurrentVehicle = (vehicle: Vehicle) => {
    currentVehicle.value = vehicle
  }

  const setSelectedVehicles = (vehicleList: Vehicle[]) => {
    selectedVehicles.value = vehicleList
  }

  const toggleVehicleSelection = (vehicleId: string) => {
    const vehicle = vehicles.value.find(v => v.id === vehicleId)
    if (vehicle) {
      vehicle.selected = !vehicle.selected
    }
  }

  const selectAllVehicles = (selected: boolean) => {
    vehicles.value.forEach(vehicle => {
      vehicle.selected = selected
    })
  }

  const addVehicle = (vehicle: Omit<Vehicle, 'selected'>) => {
    vehicles.value.push({ ...vehicle, selected: false })
  }

  const updateVehicle = (vehicleId: string, updates: Partial<Vehicle>) => {
    const index = vehicles.value.findIndex(v => v.id === vehicleId)
    if (index !== -1) {
      vehicles.value[index] = { ...vehicles.value[index], ...updates }
    }
  }

  const deleteVehicle = (vehicleId: string) => {
    const index = vehicles.value.findIndex(v => v.id === vehicleId)
    if (index !== -1) {
      vehicles.value.splice(index, 1)
    }
  }

  const setActiveTab = (tab: string) => {
    activeTab.value = tab
  }

  const setViewMode = (mode: 'list' | 'group' | 'compare') => {
    viewMode.value = mode
  }

  const setGroupBy = (group: 'riskLevel' | 'model' | 'fleet') => {
    groupBy.value = group
  }

  const updateVehicleRisk = (vehicleId: string, riskLevel: 'low' | 'warning' | 'high') => {
    const vehicle = vehicles.value.find(v => v.id === vehicleId)
    if (vehicle) {
      vehicle.riskLevel = riskLevel
    }
  }

  const calculateCTI = (thmVector: [number, number, number]) => {
    // 模拟CTI计算
    const baseVector = [0.83, 0.65, 0.75]
    const distance = Math.sqrt(
        Math.pow(thmVector[0] - baseVector[0], 2) +
        Math.pow(thmVector[1] - baseVector[1], 2) +
        Math.pow(thmVector[2] - baseVector[2], 2)
    )
    return Math.round(distance * 1000) / 1000
  }

  const calculateCBI = (remainingPower: number, requiredEnergy: number) => {
    return Math.round((remainingPower / requiredEnergy) * 100) / 100
  }

  return {
    currentVehicle,
    selectedVehicles,
    activeTab,
    viewMode,
    groupBy,
    vehicles,
    chargingPiles,
    dispatchQueue,
    availableChargingPiles,
    highRiskVehicles,
    groupedVehicles,
    selectedVehicleCount,
    setCurrentVehicle,
    setSelectedVehicles,
    toggleVehicleSelection,
    selectAllVehicles,
    addVehicle,
    updateVehicle,
    deleteVehicle,
    setActiveTab,
    setViewMode,
    setGroupBy,
    updateVehicleRisk,
    calculateCTI,
    calculateCBI
  }
})